package com.laivi.basic.util;

import java.util.Random;

import com.laivi.basic.common.constants.Constant;

/**
 * @author laivi.zhu@gmail.com
 * @date 2014-7-15
 * description:
 */
public class ArrayUtil {
	
	public static void swap(int[] datas,int i,int j){
		/*
		datas[i]=datas[i]^datas[j];
		datas[j]=datas[i]^datas[j];
		datas[i]=datas[i]^datas[j];
		*/
		int temp=datas[i];
		datas[i]=datas[j];
		datas[j]=temp;
	}
	
	public static <T> void swap(T[] datas,int i,int j){
		T temp=datas[i];
		datas[i]=datas[j];
		datas[j]=temp;
	}
	
	/**
	 * 获取一组随机数
	 * @param size
	 * @param isRepeat
	 * @return
	 */
	public static int[] getRandomArray(int size,boolean isRepeat){
		int[] datas=new int[size];
		Random rand=new Random();
		if(isRepeat){
			for(int i=0;i<size;i++){
				datas[i]=rand.nextInt(size-1);
			}
		}else{
			for(int i=0;i<size;i++){
				datas[i]=i;
			}
			for(int i=0;i<size/2;i++){
				int n=rand.nextInt(size-1);
				while(n==i){
					n=rand.nextInt(size-1);
				}
				int temp=datas[i];
				datas[i]=datas[n];
				datas[n]=temp;
			}
		}
		return datas;
	}
	
	/**
	 * 对象以第n个位置进行翻转
	 * @param objects
	 * @param n
	 */
	public static void turn(Object[] objects,int n){
		reverse(objects,0,n-1);
		reverse(objects,n,objects.length-1);
		reverse(objects,0,objects.length-1);
	}
	
	/**
	 * 对象中从start到end求逆
	 * @param objects
	 * @param start
	 * @param end
	 */
	public static void reverse(Object[] objects,int start,int end){
		if(start>=0 && start <=end && end<objects.length){
			while(start<=end){
				Object temp=objects[start];
				objects[start]=objects[end];
				objects[end]=temp;
				start++;
				end--;
			}
		}
	}
	
	public static void copyArray(Object[] srcArray,Object[] dstArray){
		int i=0;
		for(Object object:srcArray){
			dstArray[i++]=object;
		}
	}
	
	public static void copyArray(int[][] srcArray,int[][] dstArray){
		for(int i=0;i<srcArray.length;i++){
			for(int j=0;j<srcArray[i].length;j++){
				dstArray[i][j]=srcArray[i][j];
			}
		}
	}
	
	public static boolean equalArray(int[][] src,int[][] dst){
		for(int i=0;i<src.length;i++){
			for(int j=0;j<src[i].length;j++){
				if(src[i][j]!=dst[i][j]){
					return false;
				}
			}
		}
		return true;
	}
	
	public static String toString(int[] objects,int size){
		StringBuilder sb=new StringBuilder(Constant.EMPTY);
		int i=0;
		for(int object:objects){
			if(i>=size){
				break;
			}
			sb.append(object+Constant.Symbol.Comma);
			i++;
		}
		if(Constant.EMPTY.equals(sb.toString())){
			return Constant.EMPTY;
		}else{
			return sb.toString().substring(0, sb.toString().length()-1);
		}
	}

}
